/*
 * MD5.java
 * 
 * This file is part of Netuno Psamata.
 * 
 * CajuScript is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3, or (at your option) 
 * any later version.
 * 
 * CajuScript is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with CajuScript.  If not, see <http://www.gnu.org/licenses/>.
*/

package org.netuno.psamata.security;

import java.security.MessageDigest;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.netuno.psamata.PsamataException;

/**
 * MD5 Encoder.
 * @author eduveks
 */
public final class MD5 {
    /**
     * MD5 Encoder.
     */
    private MD5() { }
    /**
     * MD5 Encoder.
     * @param text Text to encode
     * @return Text encoded
     * @throws PsamataException Exception
     */
    public static byte[] crypt(final String text) throws PsamataException {
        try {
            if (text == null || text.length() == 0) {
                return new byte[0];
            } else {
                MessageDigest md = MessageDigest.getInstance("MD5");
                md.update(text.getBytes());
                byte[] hash = md.digest();
                return hash;
            }
        } catch (Exception e) {
            throw new PsamataException("Problem encryption MD5", e);
        }
    }

    public static String cryptHex(final String text) throws PsamataException {
    	if (text == null || text.length() == 0) {
            return "";
        }
        return new String(Hex.encodeHex(crypt(text)));
    }

    public static String cryptBase64(final String text) throws PsamataException {
    	if (text == null || text.length() == 0) {
            return "";
        }
        return new String(Base64.encodeBase64(crypt(text)));
    }
}
